﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace PreContractWeb
{
    public class Scheduler
    {
        private static System.Timers.Timer _Timer = null;
        private static bool _isRunning = false;
        //private static ArrayList _TaskList = null;

        public static bool isRunning
        {
            get { return Scheduler._isRunning; }
        }

        public static void Start()
        {
            if (_Timer != null)
            {
                _Timer.Stop();
            }
            else
            {
                _Timer = new System.Timers.Timer();
                _Timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
                _Timer.AutoReset = true;
            }
            _Timer.Interval = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ScheduleInterval"]) * 1000;//ms

            // get task list
            //_TaskList = Task.GetTaskList();
            //if (_TaskList.Count > 0)
            //{	// start timer
                _Timer.Start();
                _isRunning = true;
            //}

        }
        public static void Stop()
        {
            _Timer.Stop();
            _isRunning = false;
        }

        private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            //Check and schedule
            //Task task;
            //for (int i = 0; i < _TaskList.Count; i++)
            //{
            //    task = (Task)_TaskList[i];
            //    task.Run();
            //}

           // string test = string.Empty;
           
            //SendEmails();

            GenerateFile();
        }

        protected  static void GenerateFile()
        {
            try
            {
                string time = System.Configuration.ConfigurationManager.AppSettings["ExportTime"];
                DateTime starttime =Convert.ToDateTime( System.DateTime.Now.ToString("yyyy-MM-dd") + " " +  time);

                //if (System.DateTime.Now.AddSeconds(Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ScheduleInterval"])) > starttime
                //    && System.DateTime.Now < starttime)
                //{

                    string url = System.Configuration.ConfigurationManager.AppSettings["ExportURL"];
                    string strRet = string.Empty;

                    PreContractWeb.LotusDataRequester.GetData(url, out strRet);
                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
